package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.constants.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.upload.config.OssProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 *
 */
@Service
public class UploadService {

    @Autowired
    private OSS ossClient;
    @Autowired
    private OssProperties ossProps;


    public String uploadImage(MultipartFile file) {
        //判断file的内容是否为图片流
        try {
            InputStream inputStream = file.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);

            if(image==null){
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }


        //1.生成随机的文件名称
        //1.1 获取UUID
        String uuid = UUID.randomUUID().toString();
        //1.2 获取原文件名称
        String originalFilename = file.getOriginalFilename();
        //1.3 截取文件的后缀名称
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")); // .jpg
        //1.4 最终的文件名称
        String fileName = uuid+extName;

        //2.把图片保存到nginx的目录中
        try {
            file.transferTo(new File(LyConstants.IMAGE_PATH,fileName));

            return LyConstants.IMAGE_URL+fileName;
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }

    public Map<String,Object> ossSignature() {
        try {
            long expireTime = ossProps.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            //设置最大文件大小
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, ossProps.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, ossProps.getDir());

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<String, Object>();
            respMap.put("accessId", ossProps.getAccessKeyId());//注意：前端接收accessId的名称
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", ossProps.getDir());
            respMap.put("host", ossProps.getHost());
            respMap.put("expire", expireEndTime);//注意：前端需要使用超时时间的毫秒值，而不是秒数值

            return respMap;
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        } finally {
            ossClient.shutdown();
        }
    }
}
